use crate::utils::get_app;
use anyhow::Result;
use std::fs;
use tauri::path::BaseDirectory;
use tauri::Manager;
use tauri_plugin_sql::{Migration, MigrationKind};

pub fn db_setup() -> Result<()> {
    let app_handle = get_app()?;

    let resource_path = app_handle
        .path()
        .resolve("resources/download_manager.db", BaseDirectory::Resource)?;
    let target_path = app_handle.path().resolve("", BaseDirectory::AppData)?;

    if !target_path.exists() {
        fs::create_dir(&target_path)?;
    }

    let target_path = target_path.join("download_manager.db");

    if !target_path.exists() {
        fs::copy(resource_path, target_path)?;
    }

    Ok(())
}

pub fn get_migrations() -> Result<Vec<Migration>> {
    let migrations = vec![Migration {
        version: 1,
        description: "create download table",
        sql: r#"CREATE TABLE IF NOT EXISTS "download_table" (
                    "id" TEXT NOT NULL,
                    "url" TEXT,
                    "name" TEXT,
                    "size" NUMBER,
                    "downloaded_size" NUMBER,
                    "status" TEXT,
                    "output" TEXT,
                    "speed" NUMBER,
                    "progress" NUMBER,
                    "time" TEXT,
                    PRIMARY KEY ("id")
                );
                "#,
        kind: MigrationKind::Up,
    }];

    Ok(migrations)
}
